package jsu.blogger.controller;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jsu.blogger.pojo.BlogPostDetails;
import jsu.blogger.pojo.Result;
import jsu.blogger.pojo.UserFolder;
import jsu.blogger.service.inter.*;
import jsu.blogger.util.KeywordExtractor;
import jsu.blogger.util.ReturnResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping("post")//post才可访问
public class PostController {
    private static final Logger logger = LoggerFactory.getLogger(PostController.class);
    @Autowired
    private PostService postService;
    @Autowired
    private GetUserDataService getUserDataService;

    @Autowired
    private UserFollowService userFollowService;
    @Autowired
    private  LiveService liveService;
    @Autowired
    private CollectService collectService;

    //处理用户的收藏
    @PostMapping("processingCollection")
    public Result processingCollection(HttpServletRequest request){
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("uid校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long postId = Long.parseLong(String.valueOf(requestBody.get("postId")));
            String userFolderList=String.valueOf(requestBody.get("folderList"));
            List<Long> folderList=convertStringToList(userFolderList);
            if(folderList==null){
                return ReturnResultUtil.failure("数据异常");
            }
            logger.info("用户 --- 帖子id --- 修改的用户文件夹 ："+userId+", "+postId+", "+folderList);
          List<String> folderNames= postService.handlerPostFolders(userId,folderList,postId);
            return ReturnResultUtil.success(folderNames);
        }catch (Exception e){
            return ReturnResultUtil.failure("操作异常");
        }
    }

    private  List<Long> convertStringToList(String str) {
        // 创建一个空的列表
        List<Long> list = new ArrayList<>();

        // 去掉方括号
        str = str.trim();
        if (str.startsWith("[") && str.endsWith("]")) {
            if (str.equals("[]")) {
                return list; // 返回一个空的列表
            }
            str = str.substring(1, str.length() - 1);
        } else {
            return null; // 如果格式不正确，返回 null
        }

        // 分割字符串
        String[] items = str.split(",");

        // 遍历分割后的字符串数组，将每个元素转换为整数并添加到列表中
        for (String item : items) {
            try {
                // 去掉空格并转换为长整型
                list.add(Long.parseLong(item.trim()));
            } catch (NumberFormatException e) {
                // 如果转换失败，返回 null
                return null;
            }
        }

        return list;
    }

    //分页查询
    @PostMapping("selectFavorites")
    public Result selectFavorites(HttpServletRequest request){
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("uid校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long postId = Long.parseLong(String.valueOf(requestBody.get("postId")));
            int offset= Integer.parseInt(String.valueOf(requestBody.get("offset")));
            int count= Integer.parseInt(String.valueOf(requestBody.get("count")));
            logger.info("用户 --- 帖子id --- 查询的文件夹offset count ："+userId+", "+postId+", "+offset+", "+count);
            //分页查询用户的文件夹
           List<UserFolder> userFolders =postService.getUserFolders(userId,offset,count);
            List<Map<String, Object>> mapList=userFolders.stream()
                    .map(folder-> {
                        Map<String, Object> map = new HashMap<>();
                        map.put("folderId",folder.getFolderId());
                        map.put("folderDesc",folder.getFolderDesc());
                        map.put("userId",folder.getUserId());
                        map.put("folderName",folder.getFolderName());
                        map.put("isDefault",folder.getIsDefault());
                        map.put("visibility",folder.getVisibility());
                        map.put("lastUpdateTime",folder.getLastUpdate());
                        boolean isSelected= postService.existsByFolderIdAndPostId(folder.getFolderId(), postId);
                        int postNum=postService.countPostsByFolderId(folder.getFolderId());
                        map.put("isSelected",isSelected);
                        map.put("postNum",postNum);
                        return map;
                    })
                    .toList();
            return ReturnResultUtil.success(mapList);
        }catch (Exception e){
            return ReturnResultUtil.failure("操作异常");
        }
    }


    //newFavorites 新建博客夹
    @PostMapping("newFavorites")
    public Result newFavorites(HttpServletRequest request){
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("uid校验异常");
            }
            String newFolderName=String.valueOf(requestBody.get("newFolderName"));
            String isDefault=String.valueOf(requestBody.get("isDefault"));
            String isPublic=String.valueOf(requestBody.get("isPublic"));
            String folderDescription=String.valueOf(requestBody.get("folderDescription"));
            long userId = Long.parseLong(userIdStr);
            if(newFolderName.length()==0||newFolderName.length()>15){
                return ReturnResultUtil.failure("数据格式异常");
            }
            UserFolder userFolder=new UserFolder();
            userFolder.setUserId(userId);
            userFolder.setFolderName(newFolderName);
            if(folderDescription.length()==0){
                folderDescription=null;
            }
            userFolder.setFolderDesc(folderDescription);
            userFolder.setVisibility("true".equals(isPublic)?1:0);
            userFolder.setIsDefault("true".equals(isDefault)?0:null);
            userFolder.setLastUpdate(LocalDateTime.now());
            logger.info("用户新建文件夹--- 帖子id --- 新建的文件夹newFolderName isDefault isPublic folderDescription ："+userId+", "+newFolderName+", "+isDefault+", "+isPublic
                    +", "+folderDescription
            );
            return ReturnResultUtil.success(postService.newUserFavorites(userId,userFolder));
        }catch (Exception e){
            return ReturnResultUtil.failure("操作异常");
        }
    }


    //取消博客的点赞和踩
    //点赞和踩
    @PostMapping("like-dislike")
    public Result likeOrDislike(HttpServletRequest request){
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("uid校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long postId = Long.parseLong(String.valueOf(requestBody.get("postId")));
            boolean isLike = Boolean.parseBoolean(String.valueOf(requestBody.get("isLike")));
            logger.info((isLike ? "点赞" : "踩") + ", 用户:" + userId + ", 博客:" + postId);
            int result= postService.handlePostLike(userId,postId,isLike);
            if(result==0){
                return ReturnResultUtil.failure("操作失败");
            }
            return ReturnResultUtil.success();
        }catch (Exception e){
            return ReturnResultUtil.failure("操作异常");
        }
    }


    @PostMapping("remove-like-dislike")
    public Result removeUserLikeOrDislike(HttpServletRequest request){
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("uid校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long postId = Long.parseLong(String.valueOf(requestBody.get("postId")));
            logger.info( "取消点赞功能-用户:" + userId + ", 博客:" + postId);
            int result= postService.removeUserLikeOrDislike(userId,postId);
            if(result==0){
                return ReturnResultUtil.failure("操作失败");
            }
            return ReturnResultUtil.success();
        }catch (Exception e){
            return ReturnResultUtil.failure("操作异常");
        }
    }

    @PostMapping("getRecommendedBlogs")
    public Result getRecommendedBlogs(HttpServletRequest request, HttpServletResponse response) {
        //1.获取uid
        Long uid=request.getAttribute("uid")!=null?(Long)request.getAttribute("uid"):null;
        //2.获取请求的数据 分页查询  传递  需要的count
        Long count =(Long)request.getAttribute("count");
        Long offset =(Long)request.getAttribute("offset");
        logger.info("uid,offset,count： "+uid+", "+offset+", "+count);
        //3.数据响应
        return ReturnResultUtil.success(getBlogPostDetailsAsMap(uid,count,offset));
    }

    //deleteBlog 删除博客
    @PostMapping("deleteBlog")
    public Result deleteBlog(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("用户数据校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long postId = Long.parseLong(String.valueOf(requestBody.get("postId")));
            logger.info("删除用户的博客 --- --- postId ："+userId+", "+postId);
            boolean isDeleted= postService.deleteBlog(userId,postId);
            if(!isDeleted){
                return ReturnResultUtil.failure("删除失败");
            }
            return ReturnResultUtil.success();
        }catch (Exception e){
            return ReturnResultUtil.failure("后端操作异常");
        }
    }


    //searchUserAllBlogs
    @PostMapping("searchUserAllBlogs")
    public Result searchUserAllBlogs(HttpServletRequest request, HttpServletResponse response) {

        try {
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr==null) {
                return ReturnResultUtil.failure("uid不能为空");
            }
            //需要token验证
            Map<String, Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            String userIdStr=String.valueOf(requestBody.get("userId"));
            if(!uidStr.equals(userIdStr)){
                return ReturnResultUtil.failure("用户数据校验异常");
            }
            long userId = Long.parseLong(userIdStr);
            long offset = Long.parseLong(String.valueOf(requestBody.get("offset")));
            long count = Long.parseLong(String.valueOf(requestBody.get("count")));
            if(count<=0|| offset<0){
                return ReturnResultUtil.failure("请求数据异常");
            }
            logger.info("分页查询用户的博客 --- offset --- count ："+userId+", "+offset+", "+count);
            List<BlogPostDetails> blogPostDetailsList=postService.searchUserAllBlogs(userId,count,offset);

            return ReturnResultUtil.success(convertToMapList(blogPostDetailsList));
        }catch (Exception e){
            return ReturnResultUtil.failure("后端操作异常");
        }
    }
    @GetMapping("/getBlogData/{id}")
    public Result getBlogData(HttpServletRequest request, @PathVariable String id) {
        try {
            Long userId=null;
            // 获取请求头中的 uid
            String uidStr = request.getHeader("uid");
            if(uidStr!=null) {
               userId = Long.parseLong(uidStr);
            }
            Long blogId = Long.parseLong(id);  // 手动转换
            if(blogId<=0){
                return ReturnResultUtil.custom(0,"此博客不存在","");
            }
            Map<String,Object> resultMap=new HashMap<>();
            //判断redis中是否存在此博客详情数据
            String authorName=null;
            BlogPostDetails blogPostDetails=postService.getBlogPostDetailsById(blogId);
            Long authorId=null;
            if(blogPostDetails!=null) {
                authorId =blogPostDetails.getUserId();
                 authorName = getUserDataService.getUsernameByUserId(authorId);
                if(authorName==null) {
                    logger.error("不存在用户错误，用户id: "+blogPostDetails.getUserId()+", 博客id:"+blogPostDetails.getPostId());
                    return ReturnResultUtil.custom(0,"数据出现异常","");
                }
            }else{
                return ReturnResultUtil.custom(0,"博客不存在","");
            }
            logger.info("获取博客交互数据"+blogId+","+userId+","+authorId);

            Map<String,Object>interactiveData=new HashMap<>();
            if(userId != null && authorId != null){
                interactiveData.put("isFollow",userFollowService.isUserFollowing(userId,authorId));
                interactiveData.put("isLike",postService.getUserPostLikeStatus(userId,blogId));
                interactiveData.put("isCollect",collectService.countUserCollectedPost(userId,blogId));
                interactiveData.put("UserDefaultFolder",postService.getDefaultUserFolder(userId));
            }
            //返回相关推荐
            String title= blogPostDetails.getTitle();
            List<String> tagNames=blogPostDetails.getTags();
            List<BlogPostDetails> blogPostDetailsList=postService.getRelevantRecommendations(KeywordExtractor.extractKeywords(title,5),tagNames);
            resultMap.put("relevantBlog",convertToMapList(blogPostDetailsList));
            resultMap.put("interactiveData",interactiveData);
            resultMap.put("authorName", authorName);
            resultMap.put("blogDetail",blogPostDetails);
            //是否增加阅读量
            resultMap.put("isIncrementReadCount",postService.incrementReadCount(userId,blogId));
            // 处理博客数据的逻辑
            return ReturnResultUtil.success(resultMap);
        } catch (NumberFormatException e) {
            logger.error("ID格式转换失败：", e);
            return ReturnResultUtil.custom(0,"ID格式错误","");
        }
    }
    private List<Map<String, Object>> convertToMapList(List<BlogPostDetails> blogPostDetailsList) {
        List<Map<String, Object>> resultList = new ArrayList<>();
        for (BlogPostDetails blogPost : blogPostDetailsList) {
            Map<String, Object> blogPostMap = new HashMap<>();
            blogPostMap.put("id", blogPost.getPostId());
            Long userId=blogPost.getUserId();
            blogPostMap.put("userId", userId);
            blogPostMap.put("title", blogPost.getTitle());
            blogPostMap.put("likesCount", blogPost.getLikesCount());
            blogPostMap.put("readCount", blogPost.getReadCount());
            blogPostMap.put("commentsCount",blogPost.getCommentsCount());
            blogPostMap.put("shareCount", blogPost.getShareCount());
            blogPostMap.put("favoriteCount", blogPost.getFavoriteCount());
            blogPostMap.put("blogDescribe", blogPost.getBlogDescribe());
            blogPostMap.put("createdAt", blogPost.getCreatedAt());
            // 获取作者名称
            String authorName = getUserDataService.getUsernameByUserId(userId);
            //  logger.info("作者名: "+authorName);
            if(authorName==null) {
                logger.error("不存在用户错误，未清除错误博客 用户id: "+userId+", 博客id:"+blogPost.getPostId());
                return null;
            }
           blogPostMap.put("authorName", authorName);
            // 将每个 BlogPostDetails 转化为 Map 后加入 resultList
            resultList.add(blogPostMap);
        }

        return resultList;
    }
    private List<Map<String, Object>> getBlogPostDetailsAsMap(Long uid, Long count,Long offset) {
        List<BlogPostDetails> blogPostDetailsList = postService.getBlogPostDetails(uid, count, offset);
        logger.info("blogPostDetailsList 获得的完整数据为:" + blogPostDetailsList);
        // 转换为 List<Map<String, Object>>
        return blogPostDetailsList.stream()
                .map(details -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("postId", details.getPostId());
                    map.put("userId", details.getUserId());
                    map.put("title", details.getTitle());
                    map.put("likesCount", details.getLikesCount());
                    // map.put("tags", details.getTags());
                    map.put("shareCount", details.getShareCount());
                    map.put("favoriteCount", details.getFavoriteCount());
                    map.put("blogDescribe", details.getBlogDescribe());
                    //map.put("haveCoverImage", details.getHaveCoverImage());
                    //有无头像
//                    Map<String, Object>  profileImage = ImgUtil.getImgAsBase64(ImgUtil.PROFILE_PICTURE_DIR_NAME+details.getUserId());
//                    if(profileImage .get("error")==null){
//                        map.put("profileImageResult",profileImage);
//                    }
//                    String profileImageUrl=ImgUtil.isImageExists(ImgUtil.PROFILE_PICTURE_DIR_NAME+details.getUserId());
//                    if(profileImageUrl!=null){
//                        map.put("haveProfileImage", true);
//                        map.put("profileImageUrl",profileImageUrl);
//                    }else{
//                        map.put("haveProfileImage", false);
//                    }
//                    String  coverImageUrl=ImgUtil.isImageExists(ImgUtil.POST_COVER_DIR_NAME+details.getPostId());
//                    if(coverImageUrl!=null) {
//                        map.put("haveCoverImage", true);
//                        map.put("coverImageUrl",coverImageUrl);
//                    }else{
//                        map.put("haveCoverImage", false);
//                    }
                    //有无封面
//                    Map<String, Object>  coverImageResult = ImgUtil.getImgAsBase64(ImgUtil.POST_COVER_DIR_NAME+details.getPostId());
//                    if(coverImageResult .get("error")==null){
//                        map.put("coverImageResult", coverImageResult);
//                    }

                    // 获取作者名称
                    String authorName = getUserDataService.getUsernameByUserId(details.getUserId());
                    //  logger.info("作者名: "+authorName);
                    if(authorName==null) {
                        logger.error("不存在用户错误，未清除错误博客 用户id: "+details.getUpdatedAt()+", 博客id:"+details.getPostId());
                        return null;
                    }
                    map.put("authorName", authorName);
                    return map;
                })
                .filter(Objects::nonNull) // 过滤掉 null 值
                .collect(Collectors.toList());
    }
    @GetMapping("/getFollowingPost/{userId}/{begin}/{count}")
    public Result getFollowingPost(@PathVariable Long userId, @PathVariable int begin, @PathVariable int count) {
        //查询关注的用户发送的博客数据
        //获取关注列表，然后取出关注的用户的postId返回
        List<Long> followingPost=liveService.getPostIdByUserId(userId,begin,count);
        List<Map<String,Object>> result=new ArrayList<>();
        followingPost.forEach(post->{
            Map<String,Object> resultMap=new HashMap<>();
            BlogPostDetails blogPostDetails=postService.getBlogPostDetailsById(post);
            if(blogPostDetails!=null) {
                Long uid = blogPostDetails.getUserId();
                String userName = getUserDataService.getUsernameByUserId(uid);
                resultMap.put("username", userName);
                resultMap.put("blog", blogPostDetails);
//                logger.info(blogPostDetails.toString());
            }
            result.add(resultMap);
        });
        return ReturnResultUtil.success(result);
    }
}
